﻿using System;
using System.Web.Helpers;
using System.Web.Mvc;
using Xoohoo.Extensions;
using Xoohoo.Models;
using Xoohoo.Models.InputModels;

namespace Xoohoo.Modules.Admin.ModelBinders
{
    public class BulletinInputModelBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var valueProvider = bindingContext.ValueProvider;

            string tempValue;
            string title;
            string content;
            bool isShow = false;
            DateTime publishDate;

            title = valueProvider.GetAttemptedValue("Title");
            content = controllerContext.HttpContext.Request.Unvalidated("Content");

            tempValue = valueProvider.GetAttemptedValue("IsShow");
            if (!tempValue.IsNullOrEmpty() && tempValue.Split(',').Length==2)
            {
                isShow = true;
            }
            tempValue = valueProvider.GetAttemptedValue("publishDate");
            if (tempValue.IsNullOrWhiteSpace() || !DateTime.TryParse(tempValue, out publishDate))
            {
                publishDate = DateTime.Now;
            }

            BulletinInput site = new BulletinInput
            {
                Title = title,
                Content = content,
                IsShow = isShow,
                PublishDate = publishDate                
            };
            return site;
        }
    }
}
